<?php
/**
 * Created by Engineer CuiLiwu.
 * Project: deal.
 * Date: 2018/6/14-17:39
 * License Hangzhou orce Technology Co., Ltd. Copyright © 2018
 */

namespace App\Listeners;

use App\Repository\Models\UserImRecord;
use App\Repository\Models\UserImNetcall;;
use App\Repository\Repositories\Interfaces\UserImRepository;
use App\Repository\Repositories\Interfaces\UserImRecordRepository;
use App\Repository\Repositories\Interfaces\UserImNetcallRepository;

use App\Repository\Repositories\UserImRepositoryEloquent;
use App\Repository\Repositories\UserImRecordRepositoryEloquent;
use App\Repository\Repositories\UserImNetcallRepositoryEloquent;
class ImListener
{
    protected $UserIm;
    protected $UserImRecord;
    protected $UserImNetcall;

    protected $api_url = [
        'getContent'  => ['post', 'history/querySessionMsg.action'],
    ];
    public function __construct(UserImRepositoryEloquent $UserIm,UserImRecordRepositoryEloquent $UserImRecord,UserImNetcallRepositoryEloquent $UserImNetcall)
    {
        $this->UserIm  = $UserIm;
        $this->UserImRecord  = $UserImRecord;
        $this->UserImNetcall = $UserImNetcall;
    }
    public function subscribe($events)
    {
        $events->listen(
            'App\Events\ImEvent',
            'App\Listeners\ImListener@record'
        );
    }

    /**
     * @param $event:data['order_id']
     * @return bool
     */
    public function record($event){
        $data = $event->data;
        // line 88 UPDATE 更新的条件
        $getUsers = [
            'im_id_a' => $data['accid_a'],
            'im_id_b' => $data['accid_b']
        ];
        $time = time();
        $params = [
            'from'=> $getUsers['im_id_a'],
            'to'  => $getUsers['im_id_b'],
            'begintime' => strval(strtotime($data['updated_at'])).'000',
            'endtime'   => isset($data['endtime'])?$data['endtime']:$time.'000',
            'limit'     => isset($data['limit'])?intval($data['limit']):100,
            'reverse'   => 2, // 1按时间正序排列，2按时间降序排列。其它返回参数414错误.默认是按降序排列
        ];
        // 查询聊天记录
        $content = http_im($this->api_url['getContent'])->send($params);
        if ($content['code']!=414) {
            // 记录下次查询的时间，提取出最后一条记录的 发送时间，更新到 UserImRecord
            if (isset($content['msgs'][0])&&count($content['msgs'])>0) {
                // 有记录即存储，无记录只更新 查询时间。
                $lastTime = date('Y-m-d H:i:s', $content['msgs'][0]['sendtime']);

                // 合并聊天记录
                $history = $this->UserImRecord->findWhere($getUsers);
                if (isset($history['data'][0])&&$history['data'][0]['content']!=NULL){
                    $oldContent = json_decode($history['data'][0]['content'],1);
                    $contentNew = array_merge($content['msgs'],$oldContent);
                }else{
                    $contentNew = $content['msgs'];
                }
                // var_dump($contentNew);
                // 存储聊天记录
                $paramsRecord = [
                    'im_id_a' => $getUsers['im_id_a'],
                    'im_id_b' => $getUsers['im_id_b'],
                    'content' => json_encode($contentNew),
                    'lastSelect_at' => date('Y-m-d H:i:s', $time),
                ];
                // 聊天记录的json 应该是追加，而不是直接覆盖更新。
                $updateOrCreate = $this->UserImRecord->updateOrCreate($getUsers, $paramsRecord);
            } else {
                $lastTime = date('Y-m-d H:i:s', $time);
            }
            if (count($content['msgs'])>=100){
                // 不删除会话，更新聊天会话的查询时间
                $updateSelect = UserImNetcall::query()->where(['accid_a' => $data['accid_a'], 'accid_b' => $data['accid_b']])->update(['updated_at' => $lastTime]);
            }else{
                // 删除之前的会话记录，避免多次扫描。打开会话的时候会增加会话。
                $updateSelect = UserImNetcall::query()->where(['accid_a' => $data['accid_a'], 'accid_b' => $data['accid_b']])->delete();

            }
            return $updateSelect;
        }else{
            return $content['desc'];
        }
    }
    public function request_post($url = '', $param = []) {
        if (empty($url) || empty($param)) {
            return false;
        }
        $curTime = time();
        $headers = array(
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
            'AppKey:8ee7f3ff3ff30c26cf1dbc22857fd8de',
            'Nonce:1',
            'CurTime:'.$curTime,
            'CheckSum:'.sha1('b4cb8b2f5b2b' . '1' . $curTime),
        );
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }
}